package progress.exa7;

import java.sql.*;

public class JdbcStudy {

    public static void main(String[] args) {
        Statement stmt=null;
        ResultSet rs=null;
        Connection conn=null;
        try{
            //加载驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url="jdbc:mysql://localhost:3306/world?&useSSL=false&serverTimezone=UTC";
            String username="root";
            String password="root";
            //建立连接
            conn = DriverManager.getConnection(url,username,password);
            //操作数据
            stmt= conn.createStatement();
            String sql = "select * from city";
            rs = stmt.executeQuery(sql);
            System.out.println("id|name|countryCode|");
            while(rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String countryCode = rs.getString("countryCode");
                System.out.println(id +" | "+name+" | "+countryCode);
            }
        }catch(ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally{
            //释放资源
            if(rs!=null){
                try{
                    rs.close();
                }catch(SQLException e){
                    e.printStackTrace();
                }
                rs=null;
            }

            if(stmt!=null){
                try{
                    stmt.close();
                } catch(SQLException e) {
                    e.printStackTrace();
                }
                stmt=null;
            }if(conn!=null){
                try{
                   conn.close();
               }catch(SQLException e){
                   e.printStackTrace();
                }
                conn=null;
            }
        }
    }

}
